package com.chujiekeji.test.fragment;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.res.AssetManager;
import android.graphics.Color;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioGroup;
import android.widget.TextView;

import org.json.JSONArray;
import com.bigkoo.pickerview.builder.OptionsPickerBuilder;
import com.bigkoo.pickerview.listener.OnOptionsSelectListener;
import com.bigkoo.pickerview.view.OptionsPickerView;
import com.chujiekeji.test.BaseApplication;
import com.chujiekeji.test.R;
import com.chujiekeji.test.adapter.HomeListAdapter;
import com.chujiekeji.test.api.ChujieApi;
import com.chujiekeji.test.bean.PageBean;
import com.chujiekeji.test.bean.ResultBean;
import com.chujiekeji.test.bean.Task;
import com.chujiekeji.test.bean.city.JsonBean;
import com.chujiekeji.test.fragment.base.BaseFragment;
import com.chujiekeji.test.pictureselector.FullyGridLayoutManager;
import com.chujiekeji.test.pictureselector.adapter.GridImageAdapter;
import com.chujiekeji.test.util.AppOperator;
import com.chujiekeji.test.util.DialogHelper;
import com.chujiekeji.test.util.TLog;
import com.chujiekeji.test.util.ToastUtil;
import com.chujiekeji.test.widget.CustomDatePicker;
import com.chujiekeji.test.widget.DateFormatUtils;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.loopj.android.http.TextHttpResponseHandler;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import cz.msebera.android.httpclient.Header;

/**
 * Created by caobotao on 16/1/4.
 */
public class PublishFragment extends BaseFragment implements View.OnClickListener,RadioGroup.OnCheckedChangeListener  {
    protected TextHttpResponseHandler mHandler;
    @BindView(R.id.et_begintime)
    TextView tvBeginTime;
    @BindView(R.id.et_endtime)
    TextView tvEndTime;
    List<LocalMedia> selectList = new ArrayList<>();
    @BindView(R.id.recycler)
    RecyclerView recyclerView;
    GridImageAdapter adapter;
    int maxSelectNum = 3;

    @BindView(R.id.submitBtn)
    Button submitBtn;
    CustomDatePicker mTimerPicker;
    int chooseMode = PictureMimeType.ofAll();
    int themeId;

    @BindView(R.id.et_title)
    EditText etTitle;

    @BindView(R.id.et_content)
    EditText etContent;

    @BindView(R.id.et_reward)
    EditText etReward;

    @BindView(R.id.et_personcount)
    EditText etPersonCount;

    @BindView(R.id.et_province)
    TextView etProvince;

    int dealType=1;
    int category=1;
    String province="";
    String city="";
    String area="";

    private ProgressDialog mDialog;


    @Override
    protected int getLayoutId() {
        return R.layout.fragment_main_publish;
    }
    public ProgressDialog showWaitDialog(int messageId) {
        String message = getResources().getString(messageId);
        if (mDialog == null) {
            mDialog = DialogHelper.getProgressDialog(getActivity(), message);
        }

        mDialog.setMessage(message);
        mDialog.show();

        return mDialog;
    }
    @Override
    public void initData() {
        mHandler = new TextHttpResponseHandler() {
            @Override
            public void onStart() {
                super.onStart();
                showWaitDialog(R.string.title_updating_save_task);
            }

            @Override
            public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
                TLog.i("PublishFrament",responseString);
                ToastUtil.showShortToast(responseString);
            }

            @Override
            public void onSuccess(int statusCode, Header[] headers, String responseString) {
                try {
                    ResultBean<PageBean<Task>> resultBean = AppOperator.createGson().fromJson(responseString, new TypeToken<ResultBean>() {
                    }.getType());

                    ToastUtil.showShortToast(resultBean.getMessage());
                } catch (Exception e) {
                    e.printStackTrace();
                    onFailure(statusCode, headers, responseString, e);
                }
            }

            @Override
            public void onFinish() {
                super.onFinish();
                if (mDialog != null && mDialog.isShowing()) mDialog.dismiss();
            }

            @Override
            public void onCancel() {
                super.onCancel();
            }
        };
        themeId = R.style.picture_default_style;
        FullyGridLayoutManager manager = new FullyGridLayoutManager(getActivity(), 4, GridLayoutManager.VERTICAL, false);
        recyclerView.setLayoutManager(manager);
        adapter = new GridImageAdapter(getActivity(), onAddPicClickListener);
        adapter.setList(selectList);
        adapter.setSelectMax(maxSelectNum);
        recyclerView.setAdapter(adapter);
        adapter.setOnItemClickListener(new GridImageAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(int position, View v) {
                LocalMedia media = selectList.get(position);
                String pictureType = media.getPictureType();
                int mediaType = PictureMimeType.pictureToVideo(pictureType);
                switch (mediaType) {
                    case 1:
                        // 预览图片
                        PictureSelector.create(PublishFragment.this).themeStyle(themeId).openExternalPreview(position, selectList);
                        break;
                    case 2:
                        // 预览视频
                        PictureSelector.create(PublishFragment.this).externalPictureVideo(media.getPath());
                        break;
                    case 3:
                        // 预览音频
                        PictureSelector.create(PublishFragment.this).externalPictureAudio(media.getPath());
                        break;
                }
            }
        });
        initTimerPicker();
        initJsonData();
    }
    private GridImageAdapter.onAddPicClickListener onAddPicClickListener = new GridImageAdapter.onAddPicClickListener() {
        @Override
        public void onAddPicClick() {
                // 进入相册 以下是例子：不需要的api可以不写
                PictureSelector.create(PublishFragment.this)
                        .openGallery(chooseMode)
                        .maxSelectNum(maxSelectNum)
                        .minSelectNum(1)
                        .selectionMode(PictureConfig.MULTIPLE)
                        .previewImage(true)
                        .previewVideo(true)
                        .enablePreviewAudio(true) // 是否可播放音频
                        .isCamera(true)
                        .enableCrop(false)
                        .compress(false)
                        .glideOverride(160, 160)
                        .previewEggs(true)
                        .withAspectRatio(0, 0)
                        .hideBottomControls(false)
                        .isGif(false)
                        .freeStyleCropEnabled(false)
                        .circleDimmedLayer(false)
                        .showCropFrame(false)
                        .showCropGrid(false)
                        .openClickSound(true)
                        .selectionMedia(selectList)
                        .forResult(PictureConfig.CHOOSE_REQUEST);
        }
    };

    private List<JsonBean> options1Items = new ArrayList<>();
    private ArrayList<ArrayList<String>> options2Items = new ArrayList<>();
    private ArrayList<ArrayList<ArrayList<String>>> options3Items = new ArrayList<>();

    private void showPickerView() {// 弹出选择器
        OptionsPickerView pvOptions = new OptionsPickerBuilder(getContext(), new OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int options2, int options3, View v) {
                //返回的分别是三个级别的选中位置
                String opt1tx = options1Items.size() > 0 ?
                        options1Items.get(options1).getPickerViewText() : "";
                String opt2tx = options2Items.size() > 0
                        && options2Items.get(options1).size() > 0 ?
                        options2Items.get(options1).get(options2) : "";

                String opt3tx = options2Items.size() > 0
                        && options3Items.get(options1).size() > 0
                        && options3Items.get(options1).get(options2).size() > 0 ?
                        options3Items.get(options1).get(options2).get(options3) : "";

                String tx = opt1tx + opt2tx + opt3tx;
                etProvince.setText(tx);
                province=opt1tx;
                city=opt2tx;
                area=opt3tx;
            }
        }).setTitleText("城市选择")
        .setDividerColor(Color.BLACK)
        .setTextColorCenter(Color.BLACK) //设置选中项文字颜色
        .setContentTextSize(20)
        .build();
        pvOptions.setPicker(options1Items, options2Items, options3Items);//三级选择器
        pvOptions.show();
    }

    private void initJsonData() {//解析数据
        /**
         * 注意：assets 目录下的Json文件仅供参考，实际使用可自行替换文件
         * 关键逻辑在于循环体
         *
         * */
        String JsonData = getJson(getContext(), "province.json");//获取assets目录下的json文件数据
        ArrayList<JsonBean> jsonBean = parseData(JsonData);//用Gson 转成实体
        /**
         * 添加省份数据
         *
         * 注意：如果是添加的JavaBean实体，则实体类需要实现 IPickerViewData 接口，
         * PickerView会通过getPickerViewText方法获取字符串显示出来。
         */
        options1Items = jsonBean;
        for (int i = 0; i < jsonBean.size(); i++) {//遍历省份
            ArrayList<String> cityList = new ArrayList<>();//该省的城市列表（第二级）
            ArrayList<ArrayList<String>> province_AreaList = new ArrayList<>();//该省的所有地区列表（第三极）
            for (int c = 0; c < jsonBean.get(i).getCityList().size(); c++) {//遍历该省份的所有城市
                String cityName = jsonBean.get(i).getCityList().get(c).getName();
                cityList.add(cityName);//添加城市
                ArrayList<String> city_AreaList = new ArrayList<>();//该城市的所有地区列表
                //如果无地区数据，建议添加空字符串，防止数据为null 导致三个选项长度不匹配造成崩溃
                if (jsonBean.get(i).getCityList().get(c).getArea() == null
                        || jsonBean.get(i).getCityList().get(c).getArea().size() == 0) {
                    city_AreaList.add("");
                } else {
                    city_AreaList.addAll(jsonBean.get(i).getCityList().get(c).getArea());
                }
                city_AreaList.addAll(jsonBean.get(i).getCityList().get(c).getArea());
                province_AreaList.add(city_AreaList);//添加该省所有地区数据
            }

            /**
             * 添加城市数据
             */
            options2Items.add(cityList);

            /**
             * 添加地区数据
             */
            options3Items.add(province_AreaList);
        }
    }

    public ArrayList<JsonBean> parseData(String result) {//Gson 解析
        ArrayList<JsonBean> detail = new ArrayList<>();
        try {
            JSONArray data = new JSONArray(result);
            Gson gson = new Gson();
            for (int i = 0; i < data.length(); i++) {
                JsonBean entity = gson.fromJson(data.optJSONObject(i).toString(), JsonBean.class);
                detail.add(entity);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return detail;
    }
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK) {
            switch (requestCode) {
                case PictureConfig.CHOOSE_REQUEST:
                    // 图片选择
                    selectList = PictureSelector.obtainMultipleResult(data);
                    adapter.setList(selectList);
                    adapter.notifyDataSetChanged();
                    break;
            }
        }
    }

    @OnClick({R.id.et_begintime,R.id.et_endtime,R.id.et_province,R.id.submitBtn})
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.et_begintime:
                BaseApplication.get().hideKeyboard(getActivity());
                // 日期格式为yyyy-MM-dd HH:mm
                mTimerPicker.setId(R.id.et_begintime);
                mTimerPicker.show(tvBeginTime.getText().toString());
                break;
            case R.id.et_endtime:
                BaseApplication.get().hideKeyboard(getActivity());
                mTimerPicker.setId(R.id.et_endtime);
                mTimerPicker.show(tvEndTime.getText().toString());
                break;
            case R.id.et_province:
                // 日期格式为yyyy-MM-dd HH:mm
                BaseApplication.get().hideKeyboard(getActivity());
                showPickerView();
                break;
            case R.id.submitBtn:
                BaseApplication.get().hideKeyboard(getActivity());
                String title = etTitle.getText().toString();
                String content = etContent.getText().toString();
                String beginTime = tvBeginTime.getText().toString();
                String endTime = tvEndTime.getText().toString();
                String number = etPersonCount.getText().toString();
                String reward = etReward.getText().toString();
                String dealTypeStr = dealType+"";
                String categoryStr = category+"";
                List<String> files = new ArrayList<>();
                if (selectList !=null && selectList.size()>0){
                    for (int i=0;i<selectList.size();i++){
                        files.add(selectList.get(i).getPath());
                    }
                }
                ChujieApi.saveTask(title,content,beginTime,endTime,number,reward,dealTypeStr,categoryStr,province,city,area,files,mHandler);
                break;

        }
    }

    private void initTimerPicker() {
        final String beginTime = "2018-10-17 18:00";
        String endTime = "2050-01-01 00:00";
        String now = DateFormatUtils.long2Str(System.currentTimeMillis(),true);
        tvBeginTime.setText(now);
        tvEndTime.setText(now);

        // 通过日期字符串初始化日期，格式请用：yyyy-MM-dd HH:mm
        mTimerPicker = new CustomDatePicker(getContext(), new CustomDatePicker.Callback() {
            @Override
            public void onTimeSelected(int id,long timestamp) {
                if (id==R.id.et_begintime){
                    tvBeginTime.setText(DateFormatUtils.long2Str(timestamp, true));
                }else if (id==R.id.et_endtime){
                    tvEndTime.setText(DateFormatUtils.long2Str(timestamp, true));
                }
            }
        }, beginTime, endTime);
        // 允许点击屏幕或物理返回键关闭
        mTimerPicker.setCancelable(true);
        // 显示时和分
        mTimerPicker.setCanShowPreciseTime(true);
        // 允许循环滚动
        mTimerPicker.setScrollLoop(true);
        // 允许滚动动画
        mTimerPicker.setCanShowAnim(true);
    }



    public String getJson(Context context, String fileName) {

        StringBuilder stringBuilder = new StringBuilder();
        try {
            AssetManager assetManager = context.getAssets();
            BufferedReader bf = new BufferedReader(new InputStreamReader(
                    assetManager.open(fileName)));
            String line;
            while ((line = bf.readLine()) != null) {
                stringBuilder.append(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return stringBuilder.toString();
    }

    @Override
    public void onCheckedChanged(RadioGroup group, int checkedId) {
        switch (checkedId) {
            case R.id.radio0:
                dealType=1;
                break;
            case R.id.radio1:
                dealType=2;
                break;
            case R.id.radio2:
                category=1;
                break;
            case R.id.radio3:
                category=2;
                break;
        }
    }
}
